<script type="text/javascript" src="{{ context.STATIC_URL }}sprintf-0.7-beta1.js"></script>

<script type="text/javascript">
    var highest_loaded_id = 0;
    var autocomplete_choices = {};

    function init_flying_rows() {
        load_new_rows();
        {% if table.config.autoupdate %}
            setInterval(load_new_rows, 2000);
        {% endif %}
        setInterval(sort_rows, 2000);

        {% for column in table.columns %}
            {% if column.config.autocomplete %}
                autocomplete_choices['{{ column.name }}'] = [];
                $(function() {$("#inputcell-{{ column.name }}").autocomplete({
                    delay: 0,
                    source: autocomplete_choices['{{ column.name }}']
                })});
            {% endif %}
        {% endfor %}
        load_autocomplete_choices();
        setInterval(load_autocomplete_choices, 60000);

        {% for column in table.columns %}
            {% if column.frontend_validation %}
                validate_{{ column.name }} = {{ column.frontend_validation }};
            {% endif %}
        {% endfor %}
    }

    function push_autocomplete_value(column_name, value) {
        if (autocomplete_choices[column_name].indexOf(value) == -1) {
            autocomplete_choices[column_name].push(value);
        }
    }

    function load_autocomplete_choices() {
        var columns_space_delimited = '';
        {% for column in table.columns %}
            {% if column.config.autocomplete %}
                if (columns_space_delimited != '') {
                    columns_space_delimited += ' ';
                }
                columns_space_delimited += '{{ column.name }}';
            {% endif %}
        {% endfor %}
        var request_data = { module: '{{ table.module_name }}',
                             model: '{{ table.model_name }}',
                             columns_space_delimited : columns_space_delimited,
                             }
        $.get('{% url 'flying_rows.views.load_autocomplete_choices' %}', request_data, function(data, status) {
            for (var i in data) {
                for (var j in data[i]) {
                    push_autocomplete_value(i, data[i][j]);
                }
            }
        });
    }


    function load_new_rows() {
        var request_data = {highest_loaded_id: highest_loaded_id,
                            module: '{{ table.module_name }}',
                            model: '{{ table.model_name }}',
                            columns_space_delimited: '{{ table.columns_space_delimited }}'
                           };
        $.get('{% url 'flying_rows.views.load_new_rows' %}', request_data, function(data, status) {
            for (var i in data) {
                highest_loaded_id = Math.max(highest_loaded_id, i);
                prepend_row(data[i]);
            }
        })
    }

    function sort_rows() {
        // TODO: go to server, sort id by fields, rearrange rows
    }

    function prepend_row(row) { <!-- add new row from json data -->
        var html_code = new Array(0);
        {% for column in table.columns %}
        html_code.push(sprintf('<td><span id="datacell_%(id)s_{{ column.name }}" {% if column.config.editable %}class="editable" contenteditable="true"{% endif %} data-row-id="%(id)s" data-field-name="{{ column.name }}" data-max_length="{{ column.config.max_length }}">%({{ column.name }})s</span></td>', row));
        {% endfor %}
        html_code = sprintf('<tr id="td_%(id)s">', row) + html_code.join('\n') + '</tr>';
{#        $(sprintf('#%(id)s">', row)).animate({backgroundColor: '#0000FF'}, 'slow');#}
        $("#data").prepend(html_code);
        {% for column in table.columns %}
            $(sprintf("#datacell_%(id)s_{{ column.name }}", row)).bind('keydown', edit_keydown_handler);
        {% endfor %}
        {% for column in table.columns %}
            {% if column.frontend_validation %}
                $(sprintf("#datacell_%(id)s_{{ column.name }}", row)).attr('frontend_validation', 'true');
                $(sprintf("#datacell_%(id)s_{{ column.name }}", row)).attr('row_id', sprintf('%(id)s', row));
            {% endif %}
        {% endfor %}
        var ids = new Array(0);
        {% for column in table.columns %}
            ids.push(sprintf('datacell_%(id)s_{{ column.name }}', row));
        {% endfor %}
        var val;
        {% for column in table.columns %}
            {% if column.config.autocomplete %}
                val = row['{{ column.name }}'];
                if (autocomplete_choices['{{ column.name }}'].indexOf(val) == -1) {
                    autocomplete_choices['{{ column.name }}'].push(val);
                }
            {% endif %}
            {% if column.quick_focus %}
                $(sprintf("#datacell_%(id)s_{{ column.name }}", row)).attr('quick_focus', 'true');
            {% else %}
                $(sprintf("#datacell_%(id)s_{{ column.name }}", row)).attr('quick_focus', 'false');
            {% endif %}
        {% endfor %}
    }

    function addnew_keydown_handler(eventObj) {
        if (eventObj.keyCode == 13 || eventObj.keyCode == 9) {
            eventObj.preventDefault();
            eventObj.stopImmediatePropagation();
            var next_element = $(this).parent().next().children('input:text');
            if (eventObj.shiftKey) {
                var prev_element = $(this).parent().prev().children('input:text');
                if (prev_element.length == 1) {
                    prev_element.focus();
                }
                return;
            }
            if (next_element.length == 1) {
                next_element.focus();
            } else {
                <!-- start of local validation -->
                var id = $(this).attr('id');
                var row = new Object;
                {% for column in table.columns %}
                    $('#inputcell-{{ column.name }}').css('background-color', 'white');
                    row['{{ column.name }}'] = $('#inputcell-{{ column.name }}').val();
                {% endfor %}
                debugger;
                var ok = true;
                {% for column in table.columns %}
                    {% if column.frontend_validation %}
                        var validate = {{ column.frontend_validation }};
                        if (!validate(row)) {
                            $('#inputcell-{{ column.name }}').css('background-color', 'red');
                            ok = false;
                        }
                    {% endif %}
                {% endfor %}
                if (!ok) {
                    return;
                }
                <!-- end of local validation -->
                <!-- set default values -->
                {% for column in table.columns %}
                    {% if column.default_value %}
                        if ($("#inputcell-{{ column.name }}").val() == '') {
                            $("#inputcell-{{ column.name }}").val('{{ column.default_value }}');
                        }
                    {% endif %}
                {% endfor %}
                var request_data = {module: '{{ table.module_name }}',
                                    model: '{{ table.model_name }}',
                                    columns_space_delimited: '{{ table.columns_space_delimited }}',
                                    unique_columns: ''
                                   };
            {% for column in table.columns %}
                request_data["{{ column.name }}"] = $('#inputcell-{{ column.name }}').val();
            {% endfor %}
                $.post("{% url 'flying_rows.views.add_new_row' %}", request_data, function(data, status) {
                    if (data.success) {
                        info('Новая строка успешно сохранена');
                        {% for column in table.columns  %}
                            $('#inputcell-{{ column.name }}').val('');
                        {% endfor %}
                        $("#inputcell-{{ table.config.initial_focus }}").focus();
                    } else {
                        error("Некорректное значение: " + data.error_message);
                    }
                }).fail(function(data, status) {
                    alert("Не удалось обратиться к серверу");
                    alert(data.keys);
                    alert(status);
                });
            }
        } else if (eventObj.keyCode == 36) {
            $('#search-field').focus();
            $('#search-field').val('');
        }
    }

    function focus_next(eventObj, id) {
        if (!eventObj.shiftKey) {
            var next_element = $('#' + id).parent().next().children();
            if (next_element.length == 1) {
                next_element.focus();
            } else {
            {% ifequal table.config.focus_after_change 'add_new' %}
                $("#inputcell-{{ table.config.initial_focus }}").focus();
            {% else %}
                $("#search-field").focus();
            {% endifequal %}
            }
        } else {
            var prev_element = $('#' + id).parent().prev().children();
            if (prev_element.length == 1) {
                prev_element.focus();
            }
        }
    }

    function edit_keydown_handler(eventObj) {
        if (eventObj.keyCode == 13 || eventObj.keyCode == 9) {
            eventObj.preventDefault();
            eventObj.stopImmediatePropagation();
            <!-- start of local validation -->
            $(this).parent().css('background-color', 'white');
            if ($(this).attr('frontend_validation') == 'true') {
                var validate_function_name = 'validate_' + $(this).attr('data-field-name');
                var row = new Object;
                var row_id = $(this).attr('row_id');
                {% for column in table.columns %}
                    row['{{ column.name }}'] = $('#datacell_' + row_id + '_{{ column.name }}').text();
                {% endfor %}
                debugger;
                var ok = window[validate_function_name](row);
                if (!ok) {
                    $(this).parent().css('background-color', 'red');
                    return;
                }
            }
            <!-- end of local validation -->
            var request_data = {module: '{{ table.module_name }}',
                                model: '{{ table.model_name }}'};
            request_data["row_id"] = $(this).attr('data-row-id');
            request_data["field_name"] = $(this).attr('data-field-name');
            request_data["new_field_value"] = $(this).text();
            id = $(this).attr('id');
                var result = $.post("{% url 'flying_rows.views.update_field' %}", request_data, function(data,  status) {
                    if (data.success) {

                            focus_next(eventObj, id);

                        // $("#" + id).text(data.value);
                        info("Значение сохранено");
                    } else {
                        alert("Некорректное значение: " + data.error_message);
                        $("#" + id).text(data.value);
                        $("#" + id).focus();
                    }
                }).fail(function(data, status){
                            alert("Не удалось обратиться к серверу!");
                        });
        } else if (eventObj.keyCode == 36) {
            $('#search-field').focus();
            $('#search-field').val('');
        }
        eventObj.stopImmediatePropagation();
    }

    function debug_append(s) {
        $('#debug').append('<br>' + s);
    }

    function error(s) {
        $("#info_field").text('');
        $("#error_field").text(s);
    }

    function info(s) {
        $('#error_field').text('');
        $('#info_field').text(s);
    }

    $(document).ready(init_flying_rows);
</script>

{% if table.config.enable_search %}
    <div id="search">
        <input type="text" id="search-field" autocomplete="true">
    </div>
    <script type="text/javascript">
        function get_local_value(id) {
            var result = '';
            {% for column_name in table.config.search_by %}
                if (result != '') {
                    result += ' ';
                }
                result += $("#datacell_" + id + "_{{ column_name }}").text();
            {% endfor %}
            return result;
        }

        function search(value) {
            <!-- ajax request to server -->
            <!-- params: module model search_fields_space_delimited search_value -->
            <!-- returns: row_id -->
            var local_matched_ids = new Array;
            for (var id = 1; id <= highest_loaded_id; id ++) {
                if ($.trim(get_local_value(id)) == $.trim(value)) {
                    local_matched_ids.push(id);
                }
            }
            if (local_matched_ids.length == 1) {
                $("#search-field").val('');
                $("#datacell_" + local_matched_ids[0] + "_{{ table.config.initial_focus }}").focus();
                return;
            }
            var search_fields_space_delimited = '';
            {% for column_name in table.config.search_by %}
                if (search_fields_space_delimited != '') {
                    search_fields_space_delimited += ' ';
                }
                search_fields_space_delimited += '{{ column_name }}';
            {% endfor %}
            var request_data = { module: '{{ table.module_name }}',
                                 model: '{{ table.model_name }}',
                                 search_fields_space_delimited: search_fields_space_delimited,
                                 search_value: value,
            };
            $.get("{% url 'flying_rows.views.search' %}", request_data, function(data, status) {
                if (data.success) {
                    <!-- alert(data.row_id); -->
                    $("#search-field").val('');
                    $("#datacell_" + data.row_id + "_{{ table.config.initial_focus }}").focus();
                } else {
                    $('#inputcell-{{ table.config.initial_focus }}').focus();
                    error(data.error_message);
                }
            });
        }
        $("#search-field").bind('keydown', function(eventObj) {
            if (eventObj.keyCode == 13) {
                search($("#search-field").val());
            }
        })
        function load_search_hints(){
            var search_fields_space_delimited = '';
            {% for column_name in table.config.search_by %}
                if (search_fields_space_delimited != '') {
                    search_fields_space_delimited += ' ';
                }
                search_fields_space_delimited += '{{ column_name }}';
            {% endfor %}
            var request_data = { module: '{{ table.module_name }}',
                model: '{{ table.model_name }}',
                search_fields_space_delimited: search_fields_space_delimited,
            };
            $.get("{% url 'flying_rows.views.get_search_hints' %}", request_data, function(data, status){
                for (i in data.search_hints) {
                    search_hints.push(data.search_hints[i]);
                }
            })
        }
        function init_search_hints() {
            search_hints = new Array;
            $(function() {$("#search-field").autocomplete({
                delay: 0,
                source: search_hints
            })});
            load_search_hints();
        }
        init_search_hints();
    </script>
{% endif %}

<div id="info_field" style="color: green">
</div>

<div id="error_field" style="color: red">
</div>

<table width="100%" id="data_table">
    <colgroup>
        {% for column in table.columns %}
            <col width="{{ column.width }}">
        {% endfor %}
    </colgroup>
    <thead>
        {% for column in table.columns %}
            <th> {{ column.verbose_name }} </th>
        {% endfor %}
    </thead>

    {% block table-body %}
    <tbody>
        {% if table.config.enable_add_new %}
            <tr id="add_new_row">
                {% for column in table.columns %}
                    <td>
                        <input type="text" id="inputcell-{{ column.name }}" class="editable" {% if not column.config.autocomplete %}autocomplete="off"{% endif %} style="margin-bottom: 0" data-name="{{ column.name }}">
                    </td>
                {% endfor %}
            </tr>
        <script type="text/javascript">
            $("#add_new_row input:text").bind('keydown', addnew_keydown_handler);
        </script>
        {% endif %}
    </tbody>
    <tbody id="data">
    </tbody>
    {% endblock %}
</table>

<footer id="debug">
</footer>
